package it.uniroma3.dia.reader;

import it.uniroma3.dia.models.RatingMovie;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class FileRatingMovieRW implements IRatingMovieRW {

	private String inputPath;
	private String outputPath;

	public FileRatingMovieRW(String inputPath, String outputPath) {
		this.inputPath = inputPath;
		this.outputPath = outputPath;
	}

	@Override
	public List<RatingMovie> readRatingMovies() throws Exception {
		List<RatingMovie> ratingMovies = new ArrayList<RatingMovie>();
		String line;
		BufferedReader reader = new BufferedReader(new FileReader(inputPath) );

		while( (line = reader.readLine()) != null )
		{
			String[] parameters=line.split("\\t");
			int userID = Integer.parseInt(parameters[0]);
			int movieID = Integer.parseInt(parameters[1]);
			long timestamp = Long.parseLong(parameters[2]);
			RatingMovie ratingMovie = new RatingMovie(userID, movieID, timestamp);
			ratingMovies.add(ratingMovie);
		}
		
		reader.close();
		
		return ratingMovies;
	}

	@Override
	public void writeRatingMoviesPrediction(List<RatingMovie> ratingMovies)
			throws Exception {
		
		BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath) );
		for(RatingMovie ratingMovie : ratingMovies){
			String line = String.valueOf(ratingMovie.getPrediction());
			line += "\n";
			writer.write(line);
		}
		
		writer.close();
	}
}
